package com.jfinalnat.httpclient.processor;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.message.BasicHeader;

import com.jfinal.log.Log;
import com.jfinalnat.httpclient.sdk.PoolingHttpClientConfig;

public abstract class MethodProcessor {
	
	private static final Log LOG = Log.getLog(Class.class);

    protected MethodProcessor NEXT_METHOD;
    
    protected String TARGET_URL;
    
    public MethodProcessor() {
		this.TARGET_URL = PoolingHttpClientConfig.targetUrl;
	}

	/**
     * 根据ServletRequest生成HttpRequestBase
     * @param request
     * @return
     */
    public abstract HttpRequestBase doRequest(HttpServletRequest request);
    
    /**
     * 根据ServletRequest生成HttpRequestBase
     * @param request
     * @return
     */
    public abstract HttpRequestBase doRequest(HttpServletRequest request, String uri);

    /**
     * 处理响应
     * @param response
     * @param proxyRes
     */
    public HttpServletResponse doResponse(HttpServletResponse response, CloseableHttpResponse proxyRes) {
        // 处理消息头
        Header[] headers = proxyRes.getAllHeaders();
        if (headers != null) {
        	LOG.info("________________________response______________________________");
            for (Header header : headers) {
            	 if (header.getName().equalsIgnoreCase("Set-Cookie")) { 
         	        String value = response.getHeader("Set-Cookie");
         	        String responseValue;
         	        if (value != null) {        
         	        	responseValue = header.getValue();
         	        	value = "Jfinal-Nat=" + responseValue.substring(0,responseValue.indexOf("Path=/")+5)+ PoolingHttpClientConfig.local_cookie_path + "; " + value;
         	        } else {
         	        	responseValue = header.getValue();
         	        	value = "Jfinal-Nat=" + responseValue.substring(0,responseValue.indexOf("Path=/")+5)+ PoolingHttpClientConfig.local_cookie_path;
         	        }
            		 response.setHeader("Set-Cookie", value);
            	 } else {
            		 response.setHeader(header.getName(), header.getValue());            		 
            	 }
            	 LOG.info(header.getName()+", "+header.getValue());
            }
        }
        return response;
    }

    /**
     * 处理请求协议
     * @param request
     * @return
     */
    protected ProtocolVersion doProtocol(HttpServletRequest request) {
        String protocol = request.getProtocol();
        char[] cProtocol = protocol.toCharArray();
        // https的第4个字符是'S'
        if (cProtocol[4] == 'S') {
            String p = new String(cProtocol, 0, 5); //协议
            int major = Integer.valueOf(new String(cProtocol, 6, 1));   //major
            int minor = Integer.valueOf(new String(cProtocol, 8, 1));   //minor
            return new ProtocolVersion(p, major, minor);
        } else {
            String p = new String(cProtocol, 0, 4); //协议
            int major = Integer.valueOf(new String(cProtocol, 5, 1));   //major
            int minor = Integer.valueOf(new String(cProtocol, 7, 1));   //minor
            return new ProtocolVersion(p, major, minor);
        }
    }

    /**
     * 处理请求头
     * @param request
     * @return
     */
    protected Header[] doHeaders(HttpServletRequest request) {
        List<Header> headers = new ArrayList<Header>(16);
        Enumeration<String> names = request.getHeaderNames();
        //System.out.println("________________________client_request______________________________");
        while(names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getHeader(name);

            if (name.toLowerCase().equals("host")) { continue; }
            if (name.toLowerCase().equals("content-length")) { continue; }
            headers.add(new BasicHeader(name, value));
            //System.out.println(name+", "+value);
        }
        return headers.toArray(new Header[0]);
    }

}
